//
//  LendViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/6/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "TestViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "AFNetworking.h"
#import "SortMD5Code.h"
#import "CityPickerView.h"
#define boundary @"AaB03x" //设置边界 参数可以随便设置
//#import "TFFileUploadManager.h"

@interface TestViewController ()
@property (nonatomic, strong)UIButton * imageBtn;
@property (nonatomic, strong)UIImage * headImg;//头像
@property (nonatomic, strong)NSString * imageStr;

@end

@implementation TestViewController(networking)
- (void)postAndAsynchronousMethod
{
#pragma mark - NSURLConnection方法
//    //    192.168.0.164:84 宋电话：17604221613
//    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/homepage/index?api=api1001"];
//    NSString * timeStr = [self currentTimeStr];
//    //str
//    NSDictionary * dic = @{
//                           @"t":timeStr
//                           };
//    //sign
//    NSDictionary * signDic = @{
//                               @"t":timeStr,
//                               @"merchantNo":@"80d709a97af1b8ab"
//                               };
//    //排序
//    NSString * str = [self newWayDic:dic];
//    //base64_encode操作
//    NSString * encodeNewStr = [self base64EncodeString:str];
//    //替换字符
//    NSString * lastStr = [self replaceStr:encodeNewStr];
//    //排序
//    NSString * signStr = [self newWayDic:signDic];
//    //MD5加密
//    NSString * md5Str = [self md5:signStr];
//    NSDictionary * jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:lastStr, @"str", md5Str, @"sign", nil];
//    NSString * tempJson = [self dictionaryToJson:jsonDic];
//    NSData *postData = [tempJson dataUsingEncoding:NSUTF8StringEncoding];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    //设置请求方式
//    request.HTTPMethod = @"POST";
//    //设置请求参数
//    request.HTTPBody = postData;
//    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
//        NSString * strResult = [dictionary objectForKey:@"str"];//接到的json串str字段
//        NSString * rebackStr = [self replaceBack:strResult];//反替换
//        NSString * decodeStr = [self dencode:rebackStr];//解码
//        NSDictionary * messageDic = [self dictionaryWithJsonString:decodeStr];//str解析成功
//        NSMutableDictionary *compareDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
//        [compareDic setObject:@"80d709a97af1b8ab" forKey:@"merchantNo"];//构造新字典，用于后面进行比照
//        //排序
//        NSString * compareStr = [self compareSortKeyDictionary:compareDic];
//        //MD5加密
//        NSString * compareMd5Str = [self md5:compareStr];
//        NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
//        if ([compareMd5Str isEqualToString:signResult]) {
//            NSLog(@"成功");
//        }else{
//            NSLog(@"失败");
//        }
//    }];
//
#pragma mark - NSURLSessionDataTask方法
    /*
     NSURL *url = [NSURL URLWithString:@"http:120.78.157.132:82/index.php/homepage/index?api=api1004"];
     NSString * timeStr = [self currentTimeStr];
     // str
     NSDictionary * dic = @{
     @"t":timeStr
     };
     // 排序
     NSString * str = [self newWayDic:dic];
     // base64_encode操作
     NSString * encodeNewStr = [self base64EncodeString:str];
     // 替换字符
     NSString * lastStr = [self replaceStr:encodeNewStr];
     // sign
     NSDictionary * signDic = @{
     @"t":timeStr,
     @"merchantNo":@"80d709a97af1b8ab"
     };
     // 排序
     NSString * signStr = [self newWayDic:signDic];
     // MD5加密
     NSString * md5Str = [self md5:signStr];
     NSDictionary * jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:lastStr, @"str", md5Str, @"sign", nil];
     NSString * tempJson = [self dictionaryToJson:jsonDic];
     NSData *postData = [tempJson dataUsingEncoding:NSUTF8StringEncoding];
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
     // 设置请求方式
     request.HTTPMethod = @"POST";
     // 设置请求参数
     request.HTTPBody = postData;
     // 创建会话对象
     NSURLSession *session = [NSURLSession sharedSession];
     // 创建请求 Task
     NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:
     ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
     NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
     NSString * strResult = [dictionary objectForKey:@"str"];//接到的json串str字段
     NSString * rebackStr = [self replaceBack:strResult];//反替换
     NSString * decodeStr = [self dencode:rebackStr];//解码
     NSDictionary * messageDic = [self dictionaryWithJsonString:decodeStr];//str解析成功
     NSMutableDictionary *compareDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
     [compareDic setObject:@"80d709a97af1b8ab" forKey:@"merchantNo"];//构造新字典，用于后面进行比照
     // 排序
     NSString * compareStr = [self compareSortKeyDictionary:compareDic];
     // MD5加密
     NSString * compareMd5Str = [self md5:compareStr];
     NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
     if ([compareMd5Str isEqualToString:signResult]) {
     NSLog(@"成功");
     }else{
     NSLog(@"失败");
     }
     
     }];
     // 发送请求
     [dataTask resume];
     */
#pragma mark - AFN方法
    //时间戳
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"t":timeStr
                           };
//        //排序
//        NSString * str = [self newWayDic:dic];
//        //base64_encode操作
//        NSString * encodeNewStr = [self base64EncodeString:str];
//        //替换字符
//        NSString * lastStr = [self replaceStr:encodeNewStr];
        //sign
    NSDictionary * signDic = @{
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
//        //排序
//        NSString * signStr = [self newWayDic:signDic];
//        //MD5加密
//        NSString * md5Str = [self md5:signStr];
//        NSDictionary * jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:lastStr, @"str", md5Str, @"sign", nil];
//        NSString * tempJson = [self dictionaryToJson:jsonDic];
//        NSData *postData = [tempJson dataUsingEncoding:NSUTF8StringEncoding];
    
    
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSDictionary * tempDic = [md5Code getUploadImgWithStrDic:dic withSignDic:signDic];
    //    [[AFAppDotNetAPIClient sharedClient] POST:@"http://120.78.157.132:82/index.php/homepage/index?api=api1003" parameters:jsonDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        NSString * strResult = [responseObject objectForKey:@"str"];//接到的json串str字段
    //        NSString * rebackStr = [self replaceBack:strResult];//反替换
    //        NSString * decodeStr = [self dencode:rebackStr];//解码
    //        NSDictionary * messageDic = [self dictionaryWithJsonString:decodeStr];//str解析成功
    //        NSMutableDictionary *compareDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
    //        [compareDic setObject:@"80d709a97af1b8ab" forKey:@"merchantNo"];//构造新字典，用于后面进行比照
    //        //排序
    //        NSString * compareStr = [self compareSortKeyDictionary:compareDic];
    //        //MD5加密
    //        NSString * compareMd5Str = [self md5:compareStr];
    //        NSString * signResult = [responseObject objectForKey:@"sign"];//接到的json串sign字段
    //        if ([compareMd5Str isEqualToString:signResult]) {
    //            NSLog(@"成功");
    //        }else{
    //            NSLog(@"失败");
    //        }
    //
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //    }];
    
//    [[AFAppDotNetAPIClient sharedClient] POST:@"http://120.78.157.132:82/index.php/homepage/index?api=api1013" parameters:tempDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        NSData *data = UIImageJPEGRepresentation(self.headImg, .1);
//        NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
//        [formData appendPartWithFileData:data name:@"img" fileName:[NSString stringWithFormat:@"%ld.jpg",(NSUInteger)time] mimeType:@"image/jpeg"];
//    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSString * strResult = [responseObject objectForKey:@"str"];//接到的json串str字段
//        NSString * rebackStr = [self replaceBack:strResult];//反替换
//        NSString * decodeStr = [self dencode:rebackStr];//解码
//        NSDictionary * messageDic = [self dictionaryWithJsonString:decodeStr];//str解析成功
//        NSMutableDictionary *compareDic = [NSMutableDictionary dictionaryWithDictionary:messageDic];
//        [compareDic setObject:@"80d709a97af1b8ab" forKey:@"merchantNo"];//构造新字典，用于后面进行比照
//        //排序
//        NSString * compareStr = [self compareSortKeyDictionary:compareDic];
//        //MD5加密
//        NSString * compareMd5Str = [self md5:compareStr];
//        NSString * signResult = [responseObject objectForKey:@"sign"];//接到的json串sign字段
//        if ([compareMd5Str isEqualToString:signResult]) {
//            NSLog(@"成功");
//        }else{
//            NSLog(@"失败");
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [self showError:error];
//    }];
}
@end

@implementation TestViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取网络数据
//    [self postAndAsynchronousMethod];
    [self setStatusBarBackgroundColor:[UIColor whiteColor]];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    UIButton * getImgBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 60, 150, 30)];
//    [getImgBtn setBackgroundColor:[UIColor brownColor]];
//    [getImgBtn addTarget:self action:@selector(getImgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    [getImgBtn setBackgroundColor:[UIColor purpleColor]];
//    [self.view addSubview:getImgBtn];
//    self.imageBtn = getImgBtn;
//
//    UIButton * upLoadBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 100, 150, 30)];
//    [upLoadBtn setTitle:@"上传图片" forState:UIControlStateNormal];
//    [upLoadBtn setBackgroundColor:[UIColor purpleColor]];
//    [upLoadBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [upLoadBtn addTarget:self action:@selector(upLoadBtnClick) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:upLoadBtn];
    CityPickerView * pickerView = [[CityPickerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT)];
    pickerView.getAddress = ^(NSString * completeStr, NSString * specificStr){
//        self.censusRegisterContentLab.text = completeStr;
    };
    [pickerView showView];
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

//排序
- (NSString *)newWayDic:(NSDictionary *)dict{
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    //    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    //    NSLog(@"valueArray:%@",valueArray);
    
    
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        NSString *keyValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:keyValue];
    }
    NSMutableString * sstr = [signArray componentsJoinedByString:@","];
    //插入
    [sstr insertString:@"{" atIndex:0];
    [sstr insertString:@"}" atIndex:sstr.length];
    return sstr;
}
//base64编码
- (NSString *)base64EncodeString:(NSString *)string {
    //1.先把字符串转换为二进制数据
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    //2.对二进制数据进行base64编码，返回编码后的字符串
    return [data base64EncodedStringWithOptions:0];
}
//字符替换
- (NSString *)replaceStr:(NSString *)origenalStr{
    NSArray * needToBeReplaceArr = [NSArray arrayWithObjects:@"+", @"/", @"=", @"d", @"D", @"b", @"B", @"W", @"w", nil];
    NSArray * replaceArr = [NSArray arrayWithObjects:@"!", @"@", @"#", @"*", @"^", @"%", @"&", @"(", @")", nil];
    NSMutableString * tempString = (NSMutableString *)origenalStr;
    
    for (int y = 0; y<needToBeReplaceArr.count; y++) {
        //取出需要替换的字符进行判断
        NSString * arrTempStr = needToBeReplaceArr[y];
        //遍历需要进行替换字符串
        for (int i = 0; i<[origenalStr length]; i++) {
            char tempChar = [tempString characterAtIndex:i];
            NSString * matchingStr = [NSString stringWithFormat:@"%c", tempChar];
            if ([matchingStr isEqualToString:arrTempStr]) {
                NSRange range = {i, 1};
                tempString = [tempString stringByReplacingCharactersInRange:range withString:replaceArr[y]];
            }
        }
    }
    return tempString;
}
//MD5加密
- (NSString *)md5:(NSString *)str {
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    return digest;
}
//字典转json格式字符串：
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

//反替换
- (NSString *)replaceBack:(NSString *)getJsonStr{
    NSArray * needToBeReplaceArr = [NSArray arrayWithObjects:@"!", @"@", @"#", @"*", @"^", @"%", @"&", @"(", @")", nil];
    NSArray * replaceArr = [NSArray arrayWithObjects:@"+", @"/", @"=", @"d", @"D", @"b", @"B", @"W", @"w", nil];
    
    NSMutableString * tempString = (NSMutableString *)getJsonStr;
    for (int y = 0; y<needToBeReplaceArr.count; y++) {
        //取出需要替换的字符进行判断
        NSString * arrTempStr = needToBeReplaceArr[y];
        //遍历需要进行替换字符串
        for (int i = 0; i<[getJsonStr length]; i++) {
            char tempChar = [tempString characterAtIndex:i];
            NSString * matchingStr = [NSString stringWithFormat:@"%c", tempChar];
            if ([matchingStr isEqualToString:arrTempStr]) {
                NSRange range = {i, 1};
                tempString = [tempString stringByReplacingCharactersInRange:range withString:replaceArr[y]];
            }
        }
    }
    return tempString;
}


//json格式字符串转字典：
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//base64解码
- (NSString *)dencode:(NSString *)base64String
{
    //NSData *base64data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return string;
}

//比照时排序
- (NSString *)compareSortKeyDictionary:(NSDictionary *)dict{
    NSMutableString * ns = nil;//数组一个元素
    NSMutableArray * totalValueArr = [NSMutableArray array];//装value的数组的value集合
    //    NSMutableString * totalValueStr = nil;//装value的数组的json字符串
    NSMutableArray * tempTotalValueArr = [NSMutableArray array];;//临时
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    //    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [dict objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    //    NSLog(@"valueArray:%@",valueArray);
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        if ([valueArray[i] isKindOfClass:[NSArray class]]) {
            
            if ([valueArray[i] count]>0) {
                for (int y = 0; y<[valueArray[i] count]; y++) {
                    //将所有的key放进数组
                    NSArray *insideAllKeyArray = [valueArray[i][y] allKeys];
                    //序列化器对数组进行排序的block 返回值为排序后的数组
                    NSArray *insideAfterSortKeyArray = [insideAllKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id _Nonnull obj2) {
                        NSComparisonResult resuest = [obj1 compare:obj2];
                        return resuest;
                    }];
                    //                    NSLog(@"insideAfterSortKeyArray:%@",insideAfterSortKeyArray);
                    //通过排列的key值获取value
                    NSMutableArray *insidevalueArray = [NSMutableArray array];
                    NSString *insideValueString = nil;
                    for (NSString *insideSortsing in insideAfterSortKeyArray) {
                        if ([insideSortsing isEqualToString:@""] || insideSortsing.length == 0) {
                            insideValueString = @"";
                            [insidevalueArray addObject:insideValueString];
                        }else{
                            insideValueString = [valueArray[i][y] objectForKey:insideSortsing];
                            [insidevalueArray addObject:insideValueString];
                        }
                    }
                    //                    NSLog(@"insidevalueArray:%@",insidevalueArray);
                    NSMutableArray *insideArray = [NSMutableArray array];
                    //body的value里面的一个数组
                    for (int t = 0 ; t < insideAfterSortKeyArray.count; t++) {
                        NSString *insideArraykeyValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",insideAfterSortKeyArray[t],insidevalueArray[t]];
                        [insideArray addObject:insideArraykeyValue];
                    }
                    ns = [insideArray componentsJoinedByString:@","];
                    [totalValueArr addObject:ns];
                }
                if (totalValueArr.count>0) {
                    //                        ns = [totalValueArr componentsJoinedByString:@","];
                    for (int a = 0; a<totalValueArr.count; a++) {
                        //                            // 插入字符串
                        //                            [str insertString:@"abc" atIndex:2];
                        NSMutableString * string = totalValueArr[a];
                        [string insertString:@"{" atIndex:0];
                        [string insertString:@"}" atIndex:string.length];
                        [tempTotalValueArr addObject:string];
                    }
                    ns = [tempTotalValueArr componentsJoinedByString:@","];
                    //插入
                    [ns insertString:@"[" atIndex:0];
                    [ns insertString:@"]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }else{
                    //插入
                    [ns insertString:@"[{" atIndex:0];
                    [ns insertString:@"}]" atIndex:ns.length];
                    [valueArray replaceObjectAtIndex:i withObject:ns];
                }
                
                
            }else{
                //在这判断数组是否为空
                NSLog(@"走这里");
                NSMutableString *ns = [NSMutableString stringWithFormat:@""];
                //插入
                [ns insertString:@"[" atIndex:0];
                [ns insertString:@"]" atIndex:ns.length];
                [valueArray replaceObjectAtIndex:i withObject:ns];
            }
        }
        NSString *finalValue = [NSString stringWithFormat:@"\"%@\":\"%@\"",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:finalValue];
    }
    NSMutableString * sstr = [signArray componentsJoinedByString:@","];
    //插入
    [sstr insertString:@"{" atIndex:0];
    [sstr insertString:@"}" atIndex:sstr.length];
    
    //判断字符串中是否包含"[{，如果有，替换为[{
    if([sstr rangeOfString:@"\"[{"].location != NSNotFound) {
        NSRange range2 = [sstr rangeOfString:@"\"[{"];
        [sstr replaceCharactersInRange:range2 withString:@"[{"]; //不是range2.location
        NSRange range3 = [sstr rangeOfString:@"}]\""];
        [sstr replaceCharactersInRange:range3 withString:@"}]"];
    }
    return sstr;
    
}

- (void)getImgBtnClick:(UIButton *)sender{
    [self selectPhotoAlbumWithSelectPhotoHandle:^(UIImage *img) {
        [self.imageBtn setImage:img forState:UIControlStateNormal];
        self.headImg = img;
    }];
}

- (void)upLoadBtnClick{
    [self postAndAsynchronousMethod];
}



@end
